package com.bjf.listener;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.PropertyConfigurator;

import com.bjf.common.ComCons;
import com.bjf.commqry.common.CommonQueryConstants;
import com.bjf.commqry.util.CommonQueryUtil;
import com.bjf.exception.BJFException;
import com.bjf.util.XmlDBUtil;

public class BJFListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		try {
			initLog4j(arg0.getServletContext());
			initXmlDB(arg0.getServletContext());
			initCommonQuery(arg0.getServletContext());
		} catch (BJFException e) {
			e.printStackTrace();
		}
	}
	
	protected void initLog4j(ServletContext context)throws BJFException{
        String resource="/log4j.properties";
        Properties prop = new Properties();
        try {
            prop.load(this.getClass().getResourceAsStream(resource));
        } catch (IOException e) {
            e.printStackTrace();
        }
        PropertyConfigurator.configure(prop);
    }
	
	/**
     * init xmlDB
     *
     * @param context
     * @throws AppComException
     */
    protected void initXmlDB(ServletContext context) throws BJFException {
        String location = context
                .getInitParameter(ComCons.XMLDB_LOCATION);
        String[] metaFiles = location.split(",");
        XmlDBUtil.init(metaFiles,context);
    }

    /**
     * init CommonQuery
     *
     * @param context
     * @throws AppComException
     */
    protected void initCommonQuery(ServletContext context) throws BJFException {
        String location = context
                .getInitParameter(CommonQueryConstants.CMET_COMMONQUERY_CONFIGLOCATION);
        String[] metaFiles = location.split(",");
        CommonQueryUtil.init(metaFiles,context);
    }
}
